package com.kekezu.kppw.utils;

import android.os.SystemClock;
import android.text.format.DateUtils;

import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtil {
	public final static SimpleDateFormat SimpleDateFormat__YYYYMMDDHHMMSSSS = new SimpleDateFormat(
			"yyyy-MM-dd  HH-mm-ss-SS");
	public final static SimpleDateFormat SimpleDateFormat__YYYYMMDDHHMM = new SimpleDateFormat(
			"yyyy-MM-dd  HH:mm");
	public final static SimpleDateFormat SimpleDateFormat__YYYYMMDDHHMM_12 = new SimpleDateFormat(
			"yyyy-MM-dd  h:mm a");
	public final static SimpleDateFormat SimpleDateFormat__YYYYMMDD = new SimpleDateFormat(
			"yyyy年MM月dd日");
	public final static SimpleDateFormat SimpleDateFormat__YYYY_MM_DD = new SimpleDateFormat(
			"yyyy-MM-dd");
	public final static SimpleDateFormat SimpleDateFormat__YYYYMMDD_NOTHING = new SimpleDateFormat(
			"yyyyMMdd");
	public final static SimpleDateFormat SimpleDateFormat__YYMMDD = new SimpleDateFormat(
			"yy年MM月dd日");
	public final static SimpleDateFormat SimpleDateFormat__YYYYMM = new SimpleDateFormat(
			"yyyy年MM月");
	public final static SimpleDateFormat SimpleDateFormat__MMDD = new SimpleDateFormat(
			"MM-dd");
	public final static SimpleDateFormat SimpleDateFormat__HHMM = new SimpleDateFormat(
			"HH:mm");
	public final static SimpleDateFormat SimpleDateFormat_YYYY_MM_DD_HH_MM_SS = new SimpleDateFormat(
			"yyyyMMdd-hhmmss");

	public final static SimpleDateFormat SimpleDateFormat_YYYYMMDD_ = new SimpleDateFormat(
			"yyyy.MM.dd");

	public final static SimpleDateFormat SimpleDateFormat_YYYYMMDD_HHMMSS = new SimpleDateFormat(
			"yyyy.MM.dd HH:mm:ss");

	/**
	 * 默认返回当前时间年月日时分秒毫秒
	 * 
	 * @param sdf
	 * @return
	 */
	public static String getTimeString(SimpleDateFormat sdf, long mtime) {
		if (mtime <= 0) {
			mtime = System.currentTimeMillis();
		}
		if (sdf == null) {
			return SimpleDateFormat__YYYYMMDDHHMMSSSS.format(new Date(mtime));
		}
		return sdf.format(new Date(mtime));

	}

	;

	public static String getTimeString(SimpleDateFormat sdf, Date mtime) {
		if (mtime == null) {
			mtime = new Date();
		}
		if (sdf == null) {
			return SimpleDateFormat__YYYYMMDDHHMMSSSS.format(mtime);
		}
		return sdf.format(mtime);

	}

	;

	/**
	 * 得到一个格式比较友好的时间字符串.
	 * 
	 * @param time
	 * @return maybe return ""
	 */
	public static String getShortTime(long time) {
		try {
			Calendar calendar = Calendar.getInstance();
			Calendar calendar_now = Calendar.getInstance();
			calendar.setTimeInMillis(time);
			int hour = calendar.get(Calendar.HOUR_OF_DAY);
			int minute = calendar.get(Calendar.MINUTE);
			int day = calendar.get(Calendar.DAY_OF_MONTH);
			int month = calendar.get(Calendar.MONTH);
			int year = calendar.get(Calendar.YEAR);
			// if (calendar_now.get(Calendar.YEAR) != year) {
			// return calendar_now.get(Calendar.YEAR) - year + "年之前";
			// }
			// if (calendar_now.get(Calendar.MONTH) != month) {
			// return calendar_now.get(Calendar.MONTH) - month + "个月前";
			// }
			if (calendar_now.get(Calendar.DAY_OF_MONTH) != day) {
				if ((calendar_now.get(Calendar.DAY_OF_MONTH) - day) < 7
						&& (calendar_now.get(Calendar.DAY_OF_MONTH) - day) > 0) {
					return calendar_now.get(Calendar.DAY_OF_MONTH) - day + "天前";
				} else {
					return year + "年" + (month + 1) + "月" + (day) + "日";
				}
			}
			if (minute < 10) {
				return hour + ":0" + minute;
			} else {
				return hour + ":" + minute;
			}
		} catch (Exception e) {
			return "";
		}
	}

	public static String getShortTime(Date time) {
		return getShortTime(time.getTime());
	}

	public static String getNextDayString(int delay) {
		try {
			SimpleDateFormat format = new SimpleDateFormat("yyyy-M-dd");
			String mdate = "";
			Date d = new Date(System.currentTimeMillis());
			long myTime = (d.getTime() / 1000) + delay * 24 * 60 * 60;
			d.setTime(myTime * 1000);
			mdate = format.format(d);
			return mdate;
		} catch (Exception e) {
			return "";
		}
	}

	public static String milliSecendToHMSString(long milliSecend) {
		long totalSecond = milliSecend / 1000;
		long second = 0;
		long minute = 0;
		long hours = 0;
		long temp = totalSecond / 60;
		long temp2 = temp / 60;
		if (temp >= 60) {
			hours = temp2 % 60;
		}
		if (totalSecond >= 60) {
			minute = temp % 60;
		}
		second = totalSecond % 60;
		StringBuilder sb = new StringBuilder();
		sb.append(hours > 9 ? hours : "0" + hours);
		sb.append(":");
		sb.append(minute > 9 ? minute : "0" + minute);
		sb.append(":");
		sb.append(second > 9 ? second : "0" + second);
		return sb.toString();
	}

	public static long getDaysBetween(String fromString, String toString) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-M-dd");
		long to = 0l;
		long from = 0l;
		try {
			to = df.parse(fromString).getTime();
			from = df.parse(toString).getTime();
		} catch (ParseException e) {
			e.printStackTrace();
			return -1l;
		}
		return getDaysBetween(to, from);
	}

	public static boolean after(String dateString, int days) {
		String after30Day = getNextDayString(days);
		SimpleDateFormat df = new SimpleDateFormat("yyyy-M-dd");
		long from = 0l;
		try {
			from = df.parse(after30Day).getTime();
		} catch (ParseException e) {
			e.printStackTrace();
			return false;
		}

		Calendar tempCalendar = Calendar.getInstance();
		tempCalendar.setTime(new Date(from));

		Calendar tempCalendar2 = Calendar.getInstance();
		tempCalendar2.setTime(new Date(System.currentTimeMillis()));
		return tempCalendar2.after(tempCalendar);
	}

	/**
	 * 目标时间 是否�?当前时间�?+ days �? *
	 * 
	 * @param dateString
	 *            目标时间
	 * @param days
	 *            负数表示之前, 正数表示在这之后
	 * @return
	 */
	public static boolean before(String dateString, int days) {
		days = -1 * days;
		SimpleDateFormat df = new SimpleDateFormat("yyyy-M-dd");
		long from = 0l;
		long to = 0l;
		try {
			from = df.parse(dateString).getTime();

			String after30Day = getNextDayString(days);
			to = df.parse(after30Day).getTime();

			Calendar tempCalendar = Calendar.getInstance();
			tempCalendar.setTime(new Date(from));

			Calendar tempCalendar2 = Calendar.getInstance();
			tempCalendar2.setTime(new Date(to));
			System.out.println("DateUtil:before"
					+ (tempCalendar.get(Calendar.MONTH) + 1) + "-"
					+ tempCalendar.get(Calendar.DAY_OF_MONTH));
			System.out.println("DateUtil:before"
					+ (tempCalendar2.get(Calendar.MONTH) + 1) + "-"
					+ tempCalendar2.get(Calendar.DAY_OF_MONTH));
			return tempCalendar2.after(tempCalendar);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

	}

	public static long getDaysBetween(long to, long from) {
		return (to - from) / (1000 * 60 * 60 * 24);
	}

	public static void main(String[] args) {
		System.out.println(before("2014-3-25", -15));
	}

	/**
	 * 返回当前的时�? *
	 * 
	 * @return default DataFormat "yyyy-MM-dd HH:mm:ss"
	 */
	public static String now() {
		return getTimeString(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"),
				System.currentTimeMillis());
	}

	/**
	 * �?��是否是同�?��
	 * 
	 * @param time
	 *            default DataFormat "yyyy-MM-dd HH:mm:ss"
	 * @return
	 */
	public static boolean IsSameDay(String time) {
		String timeNow = now();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		boolean isSameDay = false;
		try {
			Calendar mCalendar1 = Calendar.getInstance();
			mCalendar1.setTime(df.parse(time));
			Calendar mCalendar2 = Calendar.getInstance();
			mCalendar2.setTime(df.parse(timeNow));
			if (mCalendar1.get(Calendar.DAY_OF_YEAR) == mCalendar2
					.get(Calendar.DAY_OF_YEAR)
					&& mCalendar1.get(Calendar.YEAR) == mCalendar2
							.get(Calendar.YEAR)) {
				isSameDay = true;
			}
		} catch (ParseException e1) {
			e1.printStackTrace();

		}
		if (time != null && time.length() > 0) {
			return isSameDay;
		}
		return false;
	}

	/**
	 * @hide Field length that can hold 999 days of time
	 */
	public static final int HUNDRED_DAY_FIELD_LEN = 19;

	private static final int SECONDS_PER_MINUTE = 60;
	private static final int SECONDS_PER_HOUR = 60 * 60;
	private static final int SECONDS_PER_DAY = 24 * 60 * 60;

	private static final Object sFormatSync = new Object();
	private static char[] sFormatStr = new char[HUNDRED_DAY_FIELD_LEN + 5];

	private static final long LARGEST_DURATION = (1000 * DateUtils.DAY_IN_MILLIS) - 1;

	static private int accumField(int amt, int suffix, boolean always,
			int zeropad) {
		if (amt > 99 || (always && zeropad >= 3)) {
			return 3 + suffix;
		}
		if (amt > 9 || (always && zeropad >= 2)) {
			return 2 + suffix;
		}
		if (always || amt > 0) {
			return 1 + suffix;
		}
		return 0;
	}

	static private int printField(char[] formatStr, int amt, char suffix,
			int pos, boolean always, int zeropad) {
		if (always || amt > 0) {
			final int startPos = pos;
			if ((always && zeropad >= 3) || amt > 99) {
				int dig = amt / 100;
				formatStr[pos] = (char) (dig + '0');
				pos++;
				amt -= (dig * 100);
			}
			if ((always && zeropad >= 2) || amt > 9 || startPos != pos) {
				int dig = amt / 10;
				formatStr[pos] = (char) (dig + '0');
				pos++;
				amt -= (dig * 10);
			}
			formatStr[pos] = (char) (amt + '0');
			pos++;
			formatStr[pos] = suffix;
			pos++;
		}
		return pos;
	}

	private static int formatDurationLocked(long duration, int fieldLen) {
		if (sFormatStr.length < fieldLen) {
			sFormatStr = new char[fieldLen];
		}

		char[] formatStr = sFormatStr;

		if (duration == 0) {
			int pos = 0;
			fieldLen -= 1;
			while (pos < fieldLen) {
				formatStr[pos++] = ' ';
			}
			formatStr[pos] = '0';
			return pos + 1;
		}

		char prefix;
		if (duration > 0) {
			prefix = '+';
		} else {
			prefix = '-';
			duration = -duration;
		}

		if (duration > LARGEST_DURATION) {
			duration = LARGEST_DURATION;
		}

		int millis = (int) (duration % 1000);
		int seconds = (int) Math.floor(duration / 1000);
		int days = 0, hours = 0, minutes = 0;

		if (seconds > SECONDS_PER_DAY) {
			days = seconds / SECONDS_PER_DAY;
			seconds -= days * SECONDS_PER_DAY;
		}
		if (seconds > SECONDS_PER_HOUR) {
			hours = seconds / SECONDS_PER_HOUR;
			seconds -= hours * SECONDS_PER_HOUR;
		}
		if (seconds > SECONDS_PER_MINUTE) {
			minutes = seconds / SECONDS_PER_MINUTE;
			seconds -= minutes * SECONDS_PER_MINUTE;
		}

		int pos = 0;

		if (fieldLen != 0) {
			int myLen = accumField(days, 1, false, 0);
			myLen += accumField(hours, 1, myLen > 0, 2);
			myLen += accumField(minutes, 1, myLen > 0, 2);
			myLen += accumField(seconds, 1, myLen > 0, 2);
			myLen += accumField(millis, 2, true, myLen > 0 ? 3 : 0) + 1;
			while (myLen < fieldLen) {
				formatStr[pos] = ' ';
				pos++;
				myLen++;
			}
		}

		formatStr[pos] = prefix;
		pos++;

		int start = pos;
		boolean zeropad = fieldLen != 0;
		pos = printField(formatStr, days, 'd', pos, false, 0);
		pos = printField(formatStr, hours, 'h', pos, pos != start, zeropad ? 2
				: 0);
		pos = printField(formatStr, minutes, 'm', pos, pos != start,
				zeropad ? 2 : 0);
		pos = printField(formatStr, seconds, 's', pos, pos != start,
				zeropad ? 2 : 0);
		pos = printField(formatStr, millis, 'm', pos, true,
				(zeropad && pos != start) ? 3 : 0);
		formatStr[pos] = 's';
		return pos + 1;
	}

	/**
	 * @hide Just for debugging; not internationalized.
	 */
	public static void formatDuration(long duration, StringBuilder builder) {
		synchronized (sFormatSync) {
			int len = formatDurationLocked(duration, 0);
			builder.append(sFormatStr, 0, len);
		}
	}

	/**
	 * @hide Just for debugging; not internationalized.
	 */
	public static void formatDuration(long duration, PrintWriter pw,
			int fieldLen) {
		synchronized (sFormatSync) {
			int len = formatDurationLocked(duration, fieldLen);
			pw.print(new String(sFormatStr, 0, len));
		}
	}

	/**
	 * @hide Just for debugging; not internationalized.
	 */
	public static void formatDuration(long duration, PrintWriter pw) {
		formatDuration(duration, pw, 0);
	}

	/**
	 * @hide Just for debugging; not internationalized.
	 */
	public static void formatDuration(long time, long now, PrintWriter pw) {
		if (time == 0) {
			pw.print("--");
			return;
		}
		formatDuration(time - now, pw, 0);
	}

	/**
	 * @hide Just for debugging; not internationalized.
	 */
	public static String formatUptime(long time) {
		final long diff = time - SystemClock.uptimeMillis();
		if (diff > 0) {
			return time + " (in " + diff + " ms)";
		}
		if (diff < 0) {
			return time + " (" + -diff + " ms ago)";
		}
		return time + " (now)";
	}

	/**
	 * Convert a System.currentTimeMillis() value to a time of day value like
	 * that printed in logs. MM-DD HH:MM:SS.MMM
	 * 
	 * @param millis
	 *            since the epoch (1/1/1970)
	 * @return String representation of the time.
	 * @hide
	 */
	public static String logTimeOfDay(long millis) {
		Calendar c = Calendar.getInstance();
		if (millis >= 0) {
			c.setTimeInMillis(millis);
			return String.format("%tm-%td %tH:%tM:%tS.%tL", c, c, c, c, c, c);
		} else {
			return Long.toString(millis);
		}
	}

	/**
	 * Convert a System.currentTimeMillis() value to a time of day value like
	 * that printed in logs. MM-DD HH:MM:SS
	 * 
	 * @param millis
	 *            since the epoch (1/1/1970)
	 * @return String representation of the time.
	 * @hide
	 */
	public static String long2String(long millis) {
		Calendar c = Calendar.getInstance();
		if (millis >= 0) {
			c.setTimeInMillis(millis);
			return String.format("%tm-%td %tH:%tM:%tS", c, c, c, c, c);
		} else {
			return Long.toString(millis);
		}
	}

	public static String getStandardDate(Date t) {
		if (t != null)
			return getStandardDate(t.getTime());
		return "";
	}

	/**
	 * 将时间戳转为代表"距现在多久之前"的字符串
	 * 
	 * @param t
	 *            时间戳
	 * @return
	 */
	public static String getStandardDate(long t) {

		StringBuffer sb = new StringBuffer();

		long time = System.currentTimeMillis() - t;
		long second = (long) Math.floor(time / 1000);// 秒前

		long minute = (long) Math.floor(time / 60 / 1000.0f);// 分钟前

		long hour = (long) Math.floor(time / 60 / 60 / 1000.0f);// 小时

		long day = (long) Math.floor(time / 24 / 60 / 60 / 1000.0f);// 天前

		if (day < 0 || hour < 0 || minute < 0 || second < 0) {
			return "不准确";
		}

		if (day > 0) {
			sb.append(day + "天");
		} else if (hour > 0) {
			if (hour >= 24) {
				sb.append("1天");
			} else {
				sb.append(hour + "小时");
			}
		} else if (minute > 0) {
			if (minute == 60) {
				sb.append("1小时");
			} else {
				sb.append(minute + "分钟");
			}
		} else {
			if (second == 60) {
				sb.append("1分钟");
			} else if (second >= 0 && second <= 10) {
				return "刚刚";
			} else {
				sb.append(second + "秒");
			}
		}
		sb.append("前");

		return sb.toString();
	}

	/**
	 * 判断两个日期是否是同一天
	 * 
	 * @param date1
	 *            date1
	 * @param date2
	 *            date2
	 * @return
	 */
	public static boolean isSameDate(Date date1, Date date2) {
		Calendar cal1 = Calendar.getInstance();
		cal1.setTime(date1);

		Calendar cal2 = Calendar.getInstance();
		cal2.setTime(date2);

		boolean isSameYear = cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR);
		boolean isSameMonth = isSameYear
				&& cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH);
		boolean isSameDate = isSameMonth
				&& cal1.get(Calendar.DAY_OF_MONTH) == cal2
						.get(Calendar.DAY_OF_MONTH);

		return isSameDate;
	}

	public static boolean isSameDate(long date1, long date2) {
		return isSameDate(new Date(date1), new Date(date2));
	}

	public static boolean isToday(long date1) {
		return isSameDate(new Date(date1), new Date(System.currentTimeMillis()));
	}

	public static boolean isCloseEnough(long l, long l1) {
		long l2 = l - l1;
		if (l2 < 0L)
			l2 = -l2;
		return l2 < 120000L;
	}

	public static boolean isCloseEnough(String l, String l1) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		long to = 0l;
		long from = 0l;
		try {
			to = df.parse(l).getTime();
			from = df.parse(l1).getTime();
		} catch (ParseException e) {
			e.printStackTrace();
			return false;
		}
		long l2 = to - from;
		if (l2 < 0L)
			l2 = -l2;
		return l2 < (5 * 60 * 1000) * 1L;
	}

	public static int compareTime(String l, String l1) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		long to = 0l;
		long from = 0l;
		try {
			to = df.parse(l).getTime();
			from = df.parse(l1).getTime();
		} catch (ParseException e) {
			e.printStackTrace();
			return -1;
		}
		if (to > from) {
			return 1;
		}
		if (to == from) {
			return 0;
		}
		return -1;
	}

	/**
	 * 获取date日期前后num的多少天的日期
	 * 
	 * @param date
	 * @param num
	 * @return
	 */
	public static String otherDay(Date date, int num) {
		String day = "";
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.set(Calendar.DATE, c.get(Calendar.DATE) + num);
		day = DateUtil.SimpleDateFormat__YYYY_MM_DD.format(c.getTime());
		return day;
	}

	/**
	 * 处理个人主页中时间显示方法
	 * 
	 * @param longtime
	 * @return
	 */
	public static String homePageTime(Long longtime) {
		String time = getTimeString(DateUtil.SimpleDateFormat__HHMM, longtime);

		Calendar calendar = Calendar.getInstance();
		Calendar calendar_now = Calendar.getInstance();
		calendar.setTimeInMillis(longtime);
		int day = calendar.get(Calendar.DAY_OF_MONTH);
		int month = calendar.get(Calendar.MONTH);
		if (calendar_now.get(Calendar.DAY_OF_MONTH) != day) {
			return (month + 1) + "-" + (day);
		}

		return time;
	}

	public static boolean isTooLong_24(Long time) {
		long nowtime = System.currentTimeMillis();
		if ((nowtime - time) > 1000 * 60 * 60 * 24 * 2) {
			return true;
		}
		return false;
	}

	public static boolean isTooLong_2(Long time) {
		long nowtime = System.currentTimeMillis();
		if ((nowtime - time) > 1000 * 60 * 60 * 2 * 2) {
			return true;
		}
		return false;
	}

	public static String clanderTodatetime(Calendar calendar, String style) {
		SimpleDateFormat formatter = new SimpleDateFormat(style);
		return formatter.format(calendar.getTime());
	}

}
